//
//  SelectCoursesVC.m
//  Menu
//
//  Created by mc on 16/4/12.
//  Copyright © 2016年 xmj. All rights reserved.
//

#import "SelectCoursesVC.h"
#import "AFNetworking.h"
#import "MJExtension.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import "SelectCoursesVC.h"
#import "SelectCoursesDetailVC.h"
#import "SelectCoursesCell.h"
#import "SelectCourses.h"


@interface SelectCoursesVC ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (assign, nonatomic) NSInteger page;
@property (nonatomic, assign) BOOL isHasData;
@property (strong, nonatomic) NSMutableArray *selectCourses;
//@property (nonatomic, strong) NSDictionary *dict;
@end

@implementation SelectCoursesVC

static NSString * const REQUESTURL = @"http://apis.haoservice.com/lifeservice/cook/query?";


- (UITableView*)tableView

{
    if(_tableView==nil) {
        _tableView= [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        __weak __typeof(self) weakSelf = self;
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [weakSelf loadData];
        }];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.page = 0;
            
            [weakSelf loadData];
        }];
    }
    return _tableView;
}


- (void)viewWillAppear:(BOOL)animated{
    
    if (_isHasData == NO) {
        [self loadData];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
   // [self tableView];
    //self.tableView.sectionHeaderHeight = 10;
    [self.view addSubview:self.tableView];
    // 调用加载数据方法
    // [self loadData];
    
}

- (void)loadData{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = NSLocalizedString(@"Loading...", @"HUD loading title");
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"menu"] = @"番茄";
    _page = self.page++;
    params[@"pn"] = [NSString stringWithFormat:@"%ld",(long)self.page++];
    NSInteger rn = 4 * _page;
    params[@"pn"] =@"1";
    params[@"rn"] = [NSString stringWithFormat:@"%ld",(long)rn];
    params[@"key"] = @"3c286dc4f120495199b4503dbb52b835";
    __weak typeof(self) weakSelf = self;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
    
    [manager GET:REQUESTURL parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [weakSelf.tableView.mj_footer endRefreshing];
        [weakSelf.tableView.mj_header endRefreshing];
        // 利用MJExtension框架进行字典转模型
        weakSelf.selectCourses = [SelectCourses mj_objectArrayWithKeyValuesArray:responseObject[@"result"]];
        // 刷新数据（若不刷新数据会显示不出）
        [weakSelf.tableView reloadData];
        weakSelf.isHasData = YES;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"" message:[error localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:nil];
        [alertView addAction:cancelAction];
        [weakSelf presentViewController:alertView animated:(YES) completion:^{
            
        }];
        
    }];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.selectCourses.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"selectCoursesCell";
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([SelectCoursesCell class]) bundle:nil] forCellReuseIdentifier:ID];
    SelectCoursesCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    cell.selectCourse = self.selectCourses[indexPath.section];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [SelectCoursesCell height];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 跳转到详情.
    SelectCoursesDetailVC * detailVC = [[SelectCoursesDetailVC alloc] init];
    //detailVC.dict = self.dict;
    detailVC.selectCourse = self.selectCourses[indexPath.section];
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationItem setBackBarButtonItem:[[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil]];
    
    [self.navigationController pushViewController: detailVC animated: YES];
    self.hidesBottomBarWhenPushed=NO;
   }

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}


@end
